package com.example.xinai.Controller;

import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.jwt.JWTUtil;
import com.example.xinai.Entity.AjaxResult;
import com.example.xinai.Entity.Request.LoginRequest;
import com.example.xinai.Entity.User;
import com.example.xinai.Service.Impl.userLoadServiceImpl;
import com.example.xinai.Util.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserLoadController {
    @Value("${jwt.secret}")
    private String secretKey;
    @Autowired
    private userLoadServiceImpl userLoadService;
    @PostMapping("/login")
    public AjaxResult userLoad(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        String telephone = loginRequest.getTelephone();
        String password = loginRequest.getPassword();
        if (ObjectUtils.isEmpty(telephone) || ObjectUtils.isEmpty(password)) {
            return AjaxResult.error("电话号码或密码不能为空");
        }

        User user = userLoadService.getUserByUsername(telephone);
        if (user == null) {
            return AjaxResult.error("用户不存在，请注册");
        }
        if(user.getPassword() == null){
            return AjaxResult.error("密码错误");
        }

        // 假设密码是 BCrypt 加密存储
        if (!BCrypt.checkpw(password, user.getPassword())) {
            return AjaxResult.error("密码错误");
        }

        // 构建 Payload
        Map<String, Object> payload = new HashMap<>();
        payload.put("telephone", telephone);
        payload.put("userId", user.getId());
        payload.put("exp", System.currentTimeMillis() + 3600_000); // 1小时过期时间

        String token = JWTUtil.createToken(payload, secretKey.getBytes());

        // 设置到 Header
        response.setHeader("Authorization", "Bearer " + token);

        // 返回结果包含 Token
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("telephone", telephone);
        result.put("username",user.getUsername());
        return AjaxResult.success(result);
    }

    @PostMapping("/register")
    public AjaxResult registy(@RequestBody LoginRequest loginRequest) {
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        String telephone = loginRequest.getTelephone();
        String confirmPassword = loginRequest.getConfirmPassword();

        if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password)) {
            return AjaxResult.error("用户名或密码不能为空");
        }
        if(ObjectUtils.isEmpty( telephone)){
            return AjaxResult.error("手机号不能为空");
        }
        if(userLoadService.getTelephone(telephone) !=0){
            return AjaxResult.error("用户已存在");
        }
        if(!password.equals(confirmPassword)){
            return AjaxResult.error("密码不一致");
        }
        //开始保存
        userLoadService.saveUser(new User(username, BCrypt.hashpw(password),telephone));
        log.info("用户注册成功");
        return AjaxResult.success();
    }

    @GetMapping("/profile")
    public AjaxResult getProfile(HttpServletRequest request) {
        String telephone = UserContext.getCurrentUser();
        User user = userLoadService.getUserByUsername(telephone);
        if (user == null) {
            return AjaxResult.error("用户不存在");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("username", user.getUsername());
        result.put("id", user.getId());
        result.put("telephone", user.getTelephone());
        return AjaxResult.success(result);
    }
}
